package cn.iocoder.yudao.module.erp.controller.admin.customeraccount;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.util.collection.MapUtils;
import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
import cn.iocoder.yudao.framework.tenant.core.service.TenantFrameworkServiceImpl;
import cn.iocoder.yudao.framework.tenant.core.util.TenantUtils;
import cn.iocoder.yudao.module.erp.controller.admin.contractinfo.vo.ContractInfoRespVO;
import cn.iocoder.yudao.module.erp.controller.admin.customerinfo.vo.CustomerInfoPageReqVO;
import cn.iocoder.yudao.module.erp.controller.admin.customerinfo.vo.CustomerInfoRespVO;
import cn.iocoder.yudao.module.erp.dal.dataobject.contractinfo.ContractInfoDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.customeraccount.CustomerAccountDetailDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.customerinfo.CustomerInfoDO;
import cn.iocoder.yudao.module.erp.dal.mysql.customeraccount.CustomerAccountMapper;
import cn.iocoder.yudao.module.erp.service.customerinfo.CustomerInfoService;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.constraints.*;
import javax.validation.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;

import cn.iocoder.yudao.module.erp.controller.admin.customeraccount.vo.*;
import cn.iocoder.yudao.module.erp.dal.dataobject.customeraccount.CustomerAccountDO;
import cn.iocoder.yudao.module.erp.service.customeraccount.CustomerAccountService;

@Tag(name = "管理后台 - 客户余额")
@RestController
@RequestMapping("/erp/customer-account")
@Validated
public class CustomerAccountController {

    @Resource
    private CustomerAccountService customerAccountService;

    @Resource
    private CustomerInfoService customerInfoService;

    @Resource
    private CustomerAccountMapper customerAccountMapper;


    @GetMapping("/calculateCustomerAccountCount")
    @Operation(summary = "重新计算每日计划量")
    public CommonResult<Boolean> calculateCustomerAccountCount() {
        //得到每日计划


        return success(customerAccountService.calculateCustomerAccountCount());
    }

    @PostMapping("/create")
    @Operation(summary = "创建客户余额")
    @PreAuthorize("@ss.hasPermission('erp:customer-account:create')")
    public CommonResult<Long> createCustomerAccount(@Valid @RequestBody CustomerAccountSaveReqVO createReqVO) {

        return success(customerAccountService.createCustomerAccount(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新客户余额")
    @PreAuthorize("@ss.hasPermission('erp:customer-account:update')")
    public CommonResult<Boolean> updateCustomerAccount(@Valid @RequestBody CustomerAccountSaveReqVO updateReqVO) {
        customerAccountService.updateCustomerAccount(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除客户余额")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('erp:customer-account:delete')")
    public CommonResult<Boolean> deleteCustomerAccount(@RequestParam("id") Long id) {
        customerAccountService.deleteCustomerAccount(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得客户余额")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('erp:customer-account:query')")
    public CommonResult<CustomerAccountRespVO> getCustomerAccount(@RequestParam("id") Long id) {
        CustomerAccountDO customerAccount = customerAccountService.getCustomerAccount(id);
        return success(BeanUtils.toBean(customerAccount, CustomerAccountRespVO.class));
    }




    @GetMapping("/get-detail")
    @Operation(summary = "获得客户余额")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('erp:customer-account:query')")
    public CommonResult<CustomerShowRespVO> getCustomerAccountDetail(@RequestParam("id") Long id) {
       // CustomerAccountDO customerAccount = customerAccountService.getCustomerAccount(id);
        CustomerInfoDO info=customerInfoService.getCustomerInfo(id);
        //获取列表
        /*Map<String,Object> query=new HashMap<>();
        query.put("customerId",customerAccount.getCustomerId());
        List<CustomerAccountDetailDO> list=customerAccountMapper.findListByMap(query);*/
        CustomerShowRespVO vo=BeanUtils.toBean(info, CustomerShowRespVO.class);
      //  vo.setCustomerName(customerInfoService.getCustomerInfo(vo.getCustomerId()).getName());
      //  vo.setDetailList(list);
        return success(vo);
    }



    @GetMapping("/page")
    @Operation(summary = "获得客户余额信息分页")
    @PreAuthorize("@ss.hasPermission('erp:customer-account:query')")
    public CommonResult<PageResult<CustomerShowRespVO>> getCustomerInfoPage(@Valid CustomerInfoPageReqVO pageReqVO) {
        PageResult<CustomerInfoDO> pageResult = customerInfoService.getCustomerAccountInfoPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, CustomerShowRespVO.class));
    }

 /*   @GetMapping("/page")
    @Operation(summary = "获得客户余额分页")
    @PreAuthorize("@ss.hasPermission('erp:customer-account:query')")
    public CommonResult<PageResult<CustomerAccountRespVO>> getCustomerAccountPage(@Valid CustomerAccountPageReqVO pageReqVO) {
        PageResult<CustomerAccountDO> pageResult = customerAccountService.getCustomerAccountPage(pageReqVO);

        if (CollUtil.isEmpty(pageResult.getList())) {
            return success(PageResult.empty(pageResult.getTotal()));
        }

        // 客户信息
        List<CustomerInfoDO> customerList = customerInfoService.getCustomerListIds(
                convertSet(pageResult.getList(), CustomerAccountDO::getCustomerId));
        Map<Long,CustomerInfoDO> customerMap=customerList.stream().collect(Collectors.toMap(CustomerInfoDO::getId, e -> e));


        return success(BeanUtils.toBean(pageResult, CustomerAccountRespVO.class, purchaseIn -> {
            MapUtils.findAndThen(customerMap, purchaseIn.getCustomerId(), cus -> purchaseIn.setCustomerName(cus.getName()));
        }));*/



       // return success(BeanUtils.toBean(pageResult, CustomerAccountRespVO.class));
    //}

    @GetMapping("/export-excel")
    @Operation(summary = "导出客户余额 Excel")
    @PreAuthorize("@ss.hasPermission('erp:customer-account:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportCustomerAccountExcel(@Valid CustomerInfoPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<CustomerInfoDO> list = customerInfoService.getCustomerInfoPage(pageReqVO).getList();

       /* List<CustomerInfoDO> customerList = customerInfoService.getCustomerListIds(
                convertSet(list, CustomerAccountDO::getCustomerId));
        Map<Long,CustomerInfoDO> customerMap=customerList.stream().collect(Collectors.toMap(CustomerInfoDO::getId, e -> e));*/

        // 导出 Excel
        ExcelUtils.write(response, "客户余额.xls", "数据", CustomerShowExcelVO.class,BeanUtils.toBean(list, CustomerShowExcelVO.class));

       /* BeanUtils.toBean(list, CustomerAccountRespVO.class,ca->{
            MapUtils.findAndThen(customerMap, ca.getCustomerId(), cus -> ca.setCustomerName(cus.getName()));
        })*/
    }

}